﻿<template>
  <div class="video-player-container">
    <el-card class="video-card">
      <template #header>
        <div class="card-header">
          <h3>视频播放器</h3>
          <el-tag type="info">{{ videoData.AspectRatio }}</el-tag>
        </div>
      </template>
      
      <!-- 视频播放区域 -->
      <div class="video-container" :style="videoContainerStyle">
        <video
          ref="videoRef"
          class="main-video"
          :style="videoStyle"
          @loadedmetadata="onVideoLoaded"
          @timeupdate="onTimeUpdate"
          @ended="onVideoEnded"
          @play="isPlaying = true"
          @pause="isPlaying = false"
          preload="metadata"
        >
          <source :src="currentVideoSrc" type="video/mp4" />
          您的浏览器不支持视频播放
        </video>
        
        <!-- 字幕层 -->
        <div class="subtitle-layer" :style="subtitleLayerStyle">
          <div
            v-for="subtitle in activeSubtitles"
            :key="subtitle.Id"
            class="subtitle-item"
            :style="getSubtitleStyle(subtitle)"
          >
            {{ subtitle.Content }}
          </div>
        </div>
        
        <!-- 播放控制覆盖层 -->
        <div class="video-controls-overlay" v-show="showControls" @click.stop>
          <div class="play-button" @click="togglePlay">
            <el-icon size="60" color="white">
              <VideoPlay v-if="!isPlaying" />
              <VideoPause v-else />
            </el-icon>
          </div>
        </div>
      </div>
      
      <!-- 控制面板 -->
      <div class="control-panel">
        <!-- 进度条 -->
        <div class="progress-section">
          <el-slider
            v-model="currentTime"
            :max="totalDuration"
            :step="0.1"
            :show-tooltip="false"
            @change="onSeek"
            class="progress-slider"
          />
          <div class="time-display">
            <span>{{ formatTime(currentTime) }}</span>
            <span>/</span>
            <span>{{ formatTime(totalDuration) }}</span>
          </div>
        </div>
        
        <!-- 控制按钮 -->
        <div class="control-buttons">
          <el-button-group>
            <el-button @click="togglePlay" :icon="isPlaying ? 'VideoPause' : 'VideoPlay'">
              {{ isPlaying ? '暂停' : '播放' }}
            </el-button>
            <el-button @click="restart" icon="RefreshLeft">重播</el-button>
            <el-button @click="toggleMute" :icon="isMuted ? 'Mute' : 'Microphone'">
              {{ isMuted ? '取消静音' : '静音' }}
            </el-button>
          </el-button-group>
          
          <!-- 音量控制 -->
          <div class="volume-control">
            <el-icon><Microphone /></el-icon>
            <el-slider
              v-model="volume"
              :max="100"
              :step="1"
              @change="onVolumeChange"
              class="volume-slider"
            />
          </div>
        </div>
        
        <!-- 视频信息 -->
        <div class="video-info">
          <el-descriptions :column="2" size="small">
            <el-descriptions-item label="视频轨道">{{ videoData.VideoTracks.length }}</el-descriptions-item>
            <el-descriptions-item label="音频轨道">{{ videoData.AudioTracks.length }}</el-descriptions-item>
            <el-descriptions-item label="字幕轨道">{{ subtitleTracks.length }}</el-descriptions-item>
            <el-descriptions-item label="总时长">{{ formatTime(totalDuration) }}</el-descriptions-item>
          </el-descriptions>
        </div>
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted, nextTick } from "vue"
import { 
  VideoPlay, 
  VideoPause, 
  Microphone, 
  Mute, 
  RefreshLeft 
} from '@element-plus/icons-vue'

const props = defineProps({
  videoData: {
    type: Object,
    required: true
  }
})

const videoRef = ref(null)
const isPlaying = ref(false)
const isMuted = ref(false)
const currentTime = ref(0)
const totalDuration = ref(0)
const volume = ref(50)
const showControls = ref(true)
const controlsTimer = ref(null)

// 计算属性
const videoTracks = computed(() => props.videoData.VideoTracks.filter(track => track.Type === 'Video'))
const subtitleTracks = computed(() => props.videoData.VideoTracks.filter(track => track.Type === 'Subtitle'))
const allSubtitles = computed(() => {
  const subtitles = []
  subtitleTracks.value.forEach(track => {
    if (track.VideoTrackClips) {
      subtitles.push(...track.VideoTrackClips)
    }
  })
  return subtitles
})

const currentVideoSrc = computed(() => {
  const videoTrack = videoTracks.value[0]
  if (videoTrack && videoTrack.VideoTrackClips && videoTrack.VideoTrackClips.length > 0) {
    return videoTrack.VideoTrackClips[0].Title
  }
  return ''
})

const activeSubtitles = computed(() => {
  return allSubtitles.value.filter(subtitle => 
    currentTime.value >= subtitle.TimelineIn && 
    currentTime.value <= subtitle.TimelineOut
  )
})

const videoContainerStyle = computed(() => {
  const aspectRatio = props.videoData.AspectRatio
  return {
    aspectRatio: aspectRatio,
    maxWidth: '500px',
    margin: '0 auto',
    position: 'relative',
    backgroundColor: '#000'
  }
})

const videoStyle = computed(() => ({
  width: '100%',
  height: '100%',
  objectFit: 'cover'
}))

const subtitleLayerStyle = computed(() => ({
  position: 'absolute',
  top: 0,
  left: 0,
  width: '100%',
  height: '100%',
  pointerEvents: 'none',
  zIndex: 10
}))

// 方法
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = Math.floor(seconds % 60)
  return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const getSubtitleStyle = (subtitle) => {
  const canvasWidth = props.videoData.FECanvas.Width
  const canvasHeight = props.videoData.FECanvas.Height
  
  return {
    position: 'absolute',
    left: `${subtitle.X * 100}%`,
    top: `${subtitle.Y * 100}%`,
    fontSize: `${(subtitle.FontSize / canvasHeight) * 100}vh`,
    color: subtitle.FontColor || subtitle.Color,
    fontFamily: subtitle.Font || 'Arial',
    fontWeight: subtitle.FontFace?.Bold ? 'bold' : 'normal',
    fontStyle: subtitle.FontFace?.Italic ? 'italic' : 'normal',
    textDecoration: subtitle.FontFace?.Underline ? 'underline' : 'none',
    textAlign: subtitle.Alignment?.toLowerCase() || 'left',
    lineHeight: 1.2,
    whiteSpace: 'pre-line',
    textShadow: subtitle.Outline > 0 ? 
      `0 0 ${subtitle.Outline}px ${subtitle.OutlineColour}` : 'none',
    opacity: subtitle.FontColorOpacity || 1,
    transform: `rotate(${subtitle.Angle || 0}deg)`,
    letterSpacing: `${subtitle.Spacing || 0}px`
  }
}

const togglePlay = async () => {
  if (!videoRef.value) return
  
  if (isPlaying.value) {
    videoRef.value.pause()
  } else {
    try {
      await videoRef.value.play()
    } catch (error) {
      console.error('播放失败:', error)
    }
  }
}

const restart = () => {
  if (videoRef.value) {
    videoRef.value.currentTime = 0
    currentTime.value = 0
    if (!isPlaying.value) {
      togglePlay()
    }
  }
}

const toggleMute = () => {
  if (videoRef.value) {
    videoRef.value.muted = !videoRef.value.muted
    isMuted.value = videoRef.value.muted
  }
}

const onVideoLoaded = () => {
  if (videoRef.value) {
    totalDuration.value = videoRef.value.duration
    videoRef.value.volume = volume.value / 100
  }
}

const onTimeUpdate = () => {
  if (videoRef.value) {
    currentTime.value = videoRef.value.currentTime
  }
}

const onVideoEnded = () => {
  isPlaying.value = false
  currentTime.value = 0
}

const onSeek = (value) => {
  if (videoRef.value) {
    videoRef.value.currentTime = value
    currentTime.value = value
  }
}

const onVolumeChange = (value) => {
  if (videoRef.value) {
    videoRef.value.volume = value / 100
    volume.value = value
  }
}

const hideControls = () => {
  showControls.value = false
}

const showControlsWithTimer = () => {
  showControls.value = true
  if (controlsTimer.value) {
    clearTimeout(controlsTimer.value)
  }
  controlsTimer.value = setTimeout(hideControls, 3000)
}

// 生命周期
onMounted(() => {
  if (videoRef.value) {
    videoRef.value.addEventListener('click', togglePlay)
    videoRef.value.addEventListener('mousemove', showControlsWithTimer)
    videoRef.value.addEventListener('mouseleave', hideControls)
  }
})

onUnmounted(() => {
  if (controlsTimer.value) {
    clearTimeout(controlsTimer.value)
  }
})
</script>

<style scoped>
.video-player-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.video-card {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.video-container {
  position: relative;
  background: #000;
  border-radius: 8px;
  overflow: hidden;
  cursor: pointer;
}

.main-video {
  display: block;
  width: 100%;
  height: 100%;
}

.subtitle-layer {
  pointer-events: none;
}

.subtitle-item {
  position: absolute;
  white-space: pre-line;
  word-wrap: break-word;
  max-width: 80%;
}

.video-controls-overlay {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  background: rgba(0, 0, 0, 0.3);
  opacity: 0;
  transition: opacity 0.3s ease;
  pointer-events: none;
}

.video-container:hover .video-controls-overlay {
  opacity: 1;
  pointer-events: auto;
}

.play-button {
  cursor: pointer;
  transition: transform 0.2s ease;
}

.play-button:hover {
  transform: scale(1.1);
}

.control-panel {
  margin-top: 20px;
}

.progress-section {
  margin-bottom: 20px;
}

.progress-slider {
  margin-bottom: 10px;
}

.time-display {
  display: flex;
  justify-content: space-between;
  font-size: 14px;
  color: #666;
}

.control-buttons {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 10px;
}

.volume-control {
  display: flex;
  align-items: center;
  gap: 10px;
  min-width: 150px;
}

.volume-slider {
  flex: 1;
  max-width: 100px;
}

.video-info {
  background: #f5f7fa;
  padding: 15px;
  border-radius: 6px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .video-player-container {
    padding: 10px;
  }
  
  .control-buttons {
    flex-direction: column;
    align-items: stretch;
  }
  
  .volume-control {
    justify-content: center;
  }
}

/* 字幕样式增强 */
.subtitle-item {
  text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.8);
  line-height: 1.2;
}

/* 播放按钮动画 */
@keyframes pulse {
  0% { transform: scale(1); }
  50% { transform: scale(1.05); }
  100% { transform: scale(1); }
}

.play-button:active {
  animation: pulse 0.3s ease;
}
</style>
